<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>客户阶段管理</title>

  <link rel="stylesheet" href="/cusmanage/css/layui.css">
  <link rel="stylesheet" href="/cusmanage/css/dragslot.css">
  <link rel="stylesheet" href="/cusmanage/css/common.css">
  <link rel="stylesheet" href="/cusmanage/css/manager.css">
</head>

<style type="text/css">
  /*------------分页部分--------------*/
    .pageing-container-h{
      display: flex;
      justify-content: space-between;
      padding: 0px 20px 20px 20px;
    }
    .pageing-content-h{
      line-height: 28px;
    }
    .pageing-content-h a{
      border: 1px solid #e2e2e2;
      padding: 4px 15px;
      color: #333;
      line-height: 28px;
      border-radius: 2px; 
    }
   .current{
     background: #1E9FFF !important;
     color: #fff !important;
   }
</style>
<body>
  <div class="layui-tab layui-tab-brief" lay-filter="">
    <div class="flex align-items-center lm-header">
      <ul class="layui-tab-title">
        <li {if !$type}class="layui-this"{/if}>
          <i class="layui-icon layui-icon-cols"></i>
        </li>
        <li {if $type}class="layui-this"{/if}>
          <i class="layui-icon layui-icon-slider"></i>
        </li>
      </ul>
      <div class="flex-1 flex align-items-center" style="overflow: visible;">
        <!-- <input type="text" name="nickname" id="nickname" value="{$name}" placeholder="搜索客户昵称" class="layui-input" style="width: 200px;padding-right: 27px;"> -->
        <i class="layui-icon layui-icon-search search-nickname" style="margin-left: -25px;"></i>
        <!-- <i class="layui-icon layui-icon-form" style="position: relative;z-index: 9;right: -25px;"></i> -->
        <!-- <div class="layui-form lm-header-filter">2020-11-11 ~ 2020-11-11</div> -->
        <!-- <input type="text" name="filter" readonly placeholder="筛选" autocomplete="off" class="layui-input lm-header-filter"> -->
        <span class="layui-breadcrumb" lay-separator="|" style="margin-left: 20px;">
          <!-- <a href="javascript:;" style="cursor: text;color: #333 !important ;"><strong>共{count($externalcontact_list)}个客户</strong></a> -->
          <a href="javascript:;" style="cursor: text;color: #333 !important ;"><strong>共{$p->totalnum}个客户</strong></a>
          <a href="downexcel.html" target="_blank">下载Excel</a>
          <a href="javascript:;" onclick="location.reload()"><i class="layui-icon layui-icon-refresh" style="font-size: 12px;"></i><small>更新数据</small></a>
        </span>
      </div>
      <button type="button" class="layui-btn layui-btn-primary lmheader-set">未设置客户（{$noset_externalcontact_list}）</button>
      {if $r_type != 4}
      <button type="button" class="layui-btn layui-btn-primary levelmanager-set">设置</button>
      {/if}
    </div>
    <div class="layui-tab-content">
      <!-- 看板模式 -->
      {if $type}
        <div class="layui-tab-item">
        {else}
        <div class="layui-tab-item layui-show">
      {/if}
        <!-- 100px是顶部导航等的高度，减去之后是一屏 -->
        <div id="dragslot" class="board-container" style="height: calc(100vh - 100px);">
          <!--  -->
          {loop $level_manager as $manager}
          <div class="slot" data-id="{$manager->id}">
            <ul class="slot-list as_{$manager->id}" data-sequence="{$manager->sequence}">
              <div class="slot-title">
                <span class="name">{$manager->name}</span>
                <span class="badge"><span id="count_num_{$manager->id}">{$manager->count_num}</span>个客户</span>
              </div>
              {loop $manager->user_data as $external}
              <!-- {if $external->level_manager_id == $manager->id} -->
              <li class="slot-item" data-et_id="{$external->id}">
                <div class="slot-handler">
                  <!-- item -->
                  <div class="client-board">
                    <div class="flex align-items-center">
                      <img class="client-board-avatar" src="{$external->avatar}" alt="">
                      <div class="flex-1 client-board-info">
                        <p>{$external->name}</p>
                        <p>@微信</p>
                      </div>
                    </div>
                    <p class="client-board-text" style="margin-top: 12px;">上次跟进{$external->lastchat ? date('Y-m-d H:i:s') : '-'}</p>
                    <p class="client-board-text">客服：{$h->get_user_by_id($external->wid,$external->user_id)['name']}</p>
                    <div class="flex client-board-tags">
                      {loop $external->et_tagss as $tagss}
                      <div class="client-board-tag">{$tagArr[$tagss]}</div>
                      {/loop}
                    </div>
                    <div class="client-board-action" data-sequence="{$manager->sequence}" data-external_id="{$external->id}">...</div>
                  </div>
                </div>
              </li>
              <!-- {/if} -->
              {/loop}
            </ul>
            <input type="hidden" class="hids_{$manager->id}" value="0">
            <!-- <button type="button" onclick="page({$manager->id})" class="layui-btn layui-btn-primary" style="background-color: #c38d50;">下一页</button> -->
          </div>
          {/loop}
        </div>

      </div>
      <!-- 列表模式 -->
      {if $type}
      <div class="layui-tab-item layui-show">
        {else}
          <div class="layui-tab-item">
        {/if}
        <table class="layui-table lm-table" lay-skin="line">
          <colgroup>
          </colgroup>
          <thead>
            <tr>
              <th>全部客户</th>
              <th>客户阶段</th>
              <th>所属员工</th>
              <th>标签</th>
              <th>添加时间</th>
              <th>操作</th>
            </tr> 
          </thead>
          <tbody>
            {loop $externalcontact_list as $external}
            <tr>
              <td>
                <a href="javascript:;" class="flex lm-table-user">
                  <img src="{$external->avatar}" alt="">
                  <div class="flex-1">
                    <p>{$external->name}<span style="color: #5ec75d;">@微信</span></p>
                    <p>昵称：{$external->name}</p>
                  </div>
                </a>
              </td>
              <td>
                <div class="layui-form lm-table-level">
                  <select name="lmtlevel" id="select_lmtlevel" lay-filter="lmtlevel" data-id="{$external->id}" data-sequence="{$bh->get_sequence_by_id($external->level_manager_id)['sequence']}" value="{$bh->get_sequence_by_id($external->level_manager_id)['sequence']}">
                    <option value="0">未设置</option>
                    {loop $level_manager as $manager}
                    <option value="{$manager->sequence}" {if $manager->sequence == $bh->get_sequence_by_id($external->level_manager_id)['sequence']}selected{/if}>{$manager->name}</option>
                    {/loop}
                  </select>
                </div>
              </td>
              <td>
                <div class="service-card">
                  <i class="layui-icon layui-icon-friends"></i>{$h->get_user_by_id($external->wid,$external->user_id)['name']}
                </div>
              </td>
              <td>
                {loop $external->et_tagss as $tagss}
                <span class="layui-badge-rim lm-table-tag">{$tagArr[$tagss]}</span>
                {/loop}
              </td>
              <td>{date("Y-m-d",$external->createtime)} <br>{date("H:i:s",$external->createtime)}</td>
              <!-- <td>未完成</td> -->
              <td>
                <a href="/Addons/QyWechat/Admin/Externalcontact/customer_info-{$external->id}.html" class="layui-btn layui-btn-normal layui-btn-xs">详情</a>
              </td>
            </tr>
            {/loop}
          </tbody>
        </table>
      <div class="main-container-h pageing-container-h">
      <div class="pageing-content-h">
           <span>{$p->totalnum}条/{$p->totalpage}页</span>
      </div>
      <ul class="pageing-content-h">{P weidogsadmin}</ul>
      </div>
      </div>
    </div>
  </div>

  <!-- 筛选form -->
  <form id="lmheaderFilter" class="layui-form lm-header-filter-form" action="">
    <div class="layui-form-item">
      <label class="layui-form-label">添加时间：</label>
      <div class="layui-input-block">
        <input type="text" class="layui-input" name="startTime" id="startTime" placeholder="开始日期 ~ 结束日期" autocomplete="off">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">跟进时间：</label>
      <div class="layui-input-block">
        <input type="text" class="layui-input" name="followTime" id="followTime" placeholder="开始日期 ~ 结束日期" autocomplete="off">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">客户状态</label>
      <div class="layui-input-block">
        <select name="filterClientStatus">
          <option value="0">用户状态</option>
          {loop $level_manager as $manager}
          <option value="{$manager->sequence}">{$manager->name}</option>
          {/loop}
        </select>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="lmheaderFilterSubmit">确定</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
      </div>
    </div>
  </form>

  <!-- 选择客户企业标签 -->
  <div id="tagsPanel" style="display: none;padding: 20px;">
    {loop $eTags as $eTag}
    <p class="tags-panel-title">{$eTag->group_name}</p>
    <div class="flex tags-panel-wrap">
      {loop $eTag->etags as $etag}
      <span class="tags-panel-item" data-etagid="$etag['id']">{$etag['name']}</span>
      {/loop}
    </div>
    {/loop}
    <div style="text-align: center;margin: 20px auto 10px;">
      <button class="layui-btn layui-btn-primary layui-btn-sm tags-panel-clear" style="width: 80px;">清空</button>
      <button class="layui-btn layui-btn-normal layui-btn-sm tags-panel-confirm" style="width: 80px;">确定</button>
    </div>
  </div>
  <!-- 设置客户状态 -->
  <div id="statusPanel" style="display: none;padding: 20px;">
    <form class="layui-form" id="form3" action="" style="margin: 17px 0;">
      <input type="hidden" name="external_id" id="external_id">
      <div class="layui-inline">
        <label class="layui-form-label" style="width: auto;">选择客户状态</label>
        <div class="layui-input-inline">
          <select name="clientStatus" id="statusPanel_select" value="">
            <option value="0"></option>
            {loop $level_manager as $manager}
            <option value="{$manager->sequence}">{$manager->name}</option>
            {/loop}
          </select>
        </div>
      </div>
      <div style="text-align: right;padding: 10px 40px 20px;">
        <button onclick="layer.close(layer.index)" class="layui-btn layui-btn-primary">取消</button>
        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="updLevelManager">完成</button>
      </div>
    </form>
  </div>


<script src="/js/jquery.min.js"></script>
<script src="/cusmanage/js/layui.all.js"></script>
<script src="/cusmanage/js/dragslot.js"></script>
<script src="/cusmanage/js/common.js"></script>
<script src="/js/ajax.js"></script>
<script type="text/javascript">
    window.onload=function(){
      scrollFunc();
     }
    function scrollFunc(){
      
     $(".slot").scroll(function(e){
       var scrollTop = $(this).scrollTop();
       var ks_area = $(this).innerHeight();
       var nScrollHight = 0; //滚动距离总长(注意不是滚动条的长度)  
       nScrollHight = $(this)[0].scrollHeight;
       if(scrollTop + ks_area >= nScrollHight){
          console.log("到底了")
          page(e.currentTarget.dataset.id)
       }

     });
    }
     
     function page(id){
          var page = parseInt($(".hids_"+id).val())+1;
          myAjaxPost(false, true, 'pages.html', { id:id,page:page}, function (resp) {
               if(resp.status == 'success'){
                    var html = '';
                    var data = resp.data[0];
                    var level_manager = resp.data[1];
                    data.forEach(function(datas) {
                         html += '<li class="slot-item" data-et_id="'+datas.id+'">';
                         html += '<div class="slot-handler">';
                         html += '<div class="client-board">';
                         html += '<div class="flex align-items-center">';
                         html += '<img class="client-board-avatar" src="'+datas.avatar+'" alt="">';
                         html += '<div class="flex-1 client-board-info">';
                         html += '<p>'+datas.name+'</p>';
                         html += '<p>@微信</p>';
                         html += '</div>';
                         html += '</div>';
                         html += '<p class="client-board-text" style="margin-top: 12px;">上次跟进'+datas.lastchat+'</p>';
                         html += '<p class="client-board-text">客服：'+datas.ex_name+'</p>';
                         html += '<div class="flex client-board-tags">';
                         datas.tags.forEach(function(tag) {
                              html += '<div class="client-board-tag">'+tag+'</div>';
                         })
                         html += '</div>';
                         html += '<div class="client-board-action" data-sequence="'+level_manager.sequence+'" data-external_id="'+datas.id+'">...</div>';
                         html += '</div>';
                         html += '</div>';
                         html += '</li>';
                    })
                    $(".as_"+id).append(html);
                    $(".hids_"+id).val(page);
                    $("#count_num_"+id).html(parseInt($("#count_num_"+id).html())+data.length);
               }else{
                    tusi("暂无");
               }
          })
     }
</script>
  <script>
    // 任务看板初始化 
    $('#dragslot').dragslot({ dropCallback: function(el){ //
        // alert('dragItem : ' + el);
        // console.log(el.dragItem[0].children[0].children[0].children[4].dataset.sequence);
        let id = el.dragItem[0].dataset.et_id;
        let sequence = el.dragItem[0].parentNode.dataset.sequence;
        let dq_sequence = el.dragItem[0].getElementsByClassName('client-board-action')[0].dataset.sequence;
        console.log(id);
        console.log(sequence);
        console.log(dq_sequence);
        if(sequence && sequence != dq_sequence){
          myAjaxPost(false, true, 'update_level_manager.html', !{clientStatus:sequence, external_id:id}, function (resp) {
            if(resp.status == 'success') {
              layer.msg(resp.msg);
              
            }else{
              alert(resp.msg);
            }
          })
        }

      } 
    });

    // $(".slot-item").on('click',function(){
    //     id = $(this).data('et_id');
    //     location.href='/Addons/QyWechat/Admin/Externalcontact/customer_info-'+id+'.html';
    // })
    $('.search-nickname').on('click', function() {
          let name = $("#nickname").val();
          console.log(name);
          location.href = 'clmanage.html?name='+name;
    })
    $('.client-board-action').on('click', function() {
      let sequence = $(this).data("sequence");
      $("#statusPanel_select").val('');
      $("#statusPanel_select").val(sequence);
      let external_id = $(this).data("external_id");
      $("#external_id").val('');
      $("#external_id").val(external_id);
      layui.form.render();

      layer.open({
        title: ['设置客户状态', 'font-weight:bold;'],
        type: 1,
        area: '400px',
        shadeClose: true,
        content: $('#statusPanel')
      })
    })
    layui.use('form', function(){
      var form = layui.form;
      // 监听提交  
      form.on('submit(updLevelManager)',function(data){
        var form3 = $('#form3').serialize();
        myAjaxPost(false, true, 'update_level_manager.html', form3, function (resp) {
          console.log(resp);
          if(resp.status == 'success') {
            layer.msg(resp.msg);
              setTimeout(function(){
                window.location.reload();
              },1000);
              // layer.close(index);
          }else{
            alert(resp.msg);
          }
        });
        return false;
      })
    })

    // table中客户阶段调整
    layui.use('form', function(){
      var form = layui.form;
      
      form.on('select(lmtlevel)', function(data){
        // console.log(data.elem); //得到select原始DOM对象
        // console.log(data.value); //得到被选中的值
        // console.log(data.othis); //得到美化后的DOM对象
        // if (data.value == 0) {
        //     deleteMission()
        // }
        var select_lmtlevel = $("#select_lmtlevel");
        console.log(select_lmtlevel);
        let old_sequence = select_lmtlevel.data('sequence');
        let id = select_lmtlevel.data('id');
        let val = data.value;
        console.log(old_sequence, id,val);
        
        if(val != old_sequence){
          myAjaxPost(false, true, 'update_level_manager.html', !{clientStatus:val, external_id:id}, function (resp) {
            if(resp.status == 'success') {
              layer.msg(resp.msg);
              
            }else{
              alert(resp.msg);
            }
          })
        }
      })

      //监听提交
      form.on('submit(lmheaderFilterSubmit)', function(data){
        layer.msg(JSON.stringify(data.field));
        var str = data.field.startTime
        if (data.field.followTime) {
          str += (str ? '; ' : '') + data.field.followTime
        }
        if (data.field.filterClientStatus) {
          str += (str ? '; ' : '') + data.field.filterClientStatus
        }
        $('.lm-header-filter').val(str)
        layer.close(layer.index - 1);
        return false;
      })

    });

    function deleteMission(){
      layer.confirm('确定要删除该任务吗？', { icon: 7, title:'提示'}, function(index) {
        // confirm do something
        layer.close(index);
      });
    }

    layui.use('laydate', function(){
      var laydate = layui.laydate;

      //日期范围
      laydate.render({ elem: '#startTime' ,range: true })
      laydate.render({ elem: '#followTime' ,range: true })
    })

    $('.lm-header-filter').on('click', function() {
      layer.open({
        title: '筛选',
        type: 1,
        area: ['auto'],
        shadeClose: true,
        content: $('#lmheaderFilter')
      })
    })

    $('.lmheader-set').on('click', function() {
      layer.open({
        title: '未设置客户',
        type: 2,
        area: ['900px', '700px'],
        maxHeight: 700,
        shadeClose: true,
        content: 'set_cus_manage.html'
      })
    })

    // 筛选客户标签
    $('.tags-filter').on('click', function(e) {
      if (e.target.classList.contains('layui-icon-close')) { // 删除
        var $item = $(e.target).parent()
        var value = $item.text()
        $item.remove()
        var $panelTags = $('.tags-panel-item.on')
        for (var i = 0, l = $panelTags.length; i < l; i++) {
          if ($panelTags[i].innerText === value) {
            $($panelTags[i]).removeClass('on')
          }
        }
        if (!$('.filter-tag').length) {
          $('.tags-filter-content').html('<span class="placeholder">请选择标签</span>')
        }
      } else { // 选择标签
        layer.open({
          title: ['企业标签', 'font-weight:bold;'],
          type: 1,
          shadeClose: true,
          content: $('#tagsPanel')
        })
      }
    })
    $(document).on('click', '.tags-panel-item', function() {
      if ($(this).hasClass('disabled')) return;
      $(this).toggleClass('on')
    })
    // 清空
    $('.tags-panel-clear').on('click', function() {
      $('.tags-panel-item').removeClass('on')
      $('.tags-filter-content').html('<span class="placeholder">请选择标签</span>')
      layer.close(layer.index)
    })
    // 确定
    $('.tags-panel-confirm').on('click', function() {
      // console.log('---')
      var $tags = $('.tags-panel-item.on')
      var html = ''
      for (var i = 0, l = $tags.length; i < l; i++) {
        html += '<span class="layui-badge-rim filter-tag">' + $tags[i].innerText + '<i class="layui-icon layui-icon-close"></i></span>'
      }
      if (!html) {
        html += '<span class="placeholder">请选择标签</span>'
      }
      $('.tags-filter-content').html(html)
      layer.close(layer.index)
    })
    
    function getPageSelected() {
      var arr = layui.table.checkStatus('testTable').data
      var result = []
      for (var i = 0, l = arr.length; i < l; i++) {
        result.push(JSON.parse(arr[i].id))
      }
      return result
    }
    var currTablePage = 1, tableSelected = [] // 以页码为key，result为value
    // var panelSelectedUsers = {}
    // 弹窗-设置客户标签的table
    // layui.use('table', function(){
    //   var table = layui.table;
      
    //   table.on('checkbox(panelTable)', function(obj){
    //     console.log(obj.checked); //当前是否选中状态
    //     console.log(obj.data); //选中行的相关数据
    //     // console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one

    //     if (obj.checked) {
    //       // panelSelectedUsers[obj.data.用户id] = obj.data
    //       panelSelectedUsers['1'] = obj.data
    //     } else {
    //       // delete panelSelectedUsers[obj.data.用户id]
    //       delete panelSelectedUsers['1']
    //     }
    //   })
    // })
    // 弹窗-设置客户标签的table
    layui.use('table', function(){
      var table = layui.table;

      //转换静态表格
      table.init('panelTable', {
        page: !{limit: 1},
        // 页码变化会触发
        done: function(res, curr, count) {
          console.log('当前页码: ' + curr)
          currTablePage = curr
          // $('.mcheckbox-table td .layui-form-checked').click() // 如需翻页清除选中项
        }
      })
      
      table.on('checkbox(panelTable)', function(obj){
        var result = getPageSelected()
        tableSelected[currTablePage] = result
        // if (!result.length) delete tableSelected[currTablePage] // 如果当页没有选中值，需要删除key的话
      })
    })
    // 设置客户状态按钮
    // $('.set-client-status').on('click', function() {
    //   var ks = Object.keys(panelSelectedUsers)
    //   if (!ks.length) {
    //     layer.msg('请至少选择一个客户')
    //     return
    //   }
    //   console.log(ks);
    //   $('.client-step1').hide()
    //   $('.client-step2').fadeIn()
    // })
    // 设置客户状态按钮
    $('.set-client-status').on('click', function() {
      var result = getPageSelected()
      // console.log('result: ', result)
      // console.log('all selected: ', tableSelected)
      var id_res =  tableSelected.reduce(function (a, b) { return a.concat(b)} );
      // if (!result.length) {
      //   layer.msg('请至少选择一个客户')
      //   return
      // }
      // $('.client-step1').hide()
      // $('.client-step2').fadeIn()

      // var html = ''
      // for (var j = 0, jl = result.length; j < jl; j++) {
      //   html += '<div class=set-client-user data-id=' + result[j].id + '>< img src=' + result[j].avatar + ' alt=><span>' + result[j].name + '</span></div>'
      // }
      // $('.client-step2-users').html(html)

      // var checkedNodes = $('.mcheckbox-table [name="layTableCheckbox"]')
      // var valueNodes = $('.mcheckbox-table .panel-table-value')
      // var result = [];
      // var page = $(".mcheckbox-table .layui-laypage-curr").text();
      // console.log('page...',page);
      // var pageSize = 10;
      // 第一个是全选框，扔掉
      // for (var i = 1, l = checkedNodes.length; i < l; i++) {
      //   if (checkedNodes[i].checked) {
      //     result.push(JSON.parse(valueNodes[i - 1].innerText))
      //   }
      // }
      //处理翻页
      // var currentValueNodes = valueNodes.slice((page - 1)*pageSize)
      // for (var i = 1 , l = checkedNodes.length; i < l; i++) {
      //   if(checkedNodes[i].checked){
      //     result.push(JSON.parse(currentValueNodes[i - 1].innerText))
      //   }
      // }

      // console.log('result: ', result)

      if (!id_res.length) {
        layer.msg('请至少选择一个客户');
        return ;
      }
      $('.client-step1').hide();
      $('.client-step2').fadeIn();

      var html = '';
      var et_id = [];
      for (var j = 0, jl = id_res.length; j < jl; j++) {
        html += '<div class=set-client-user data-id=' + id_res[j].id + '><img src="' + id_res[j].avatar + '" alt=""><span>' + id_res[j].name + '</span></div>';
        et_id.push(id_res[j].id);
      }
      $('.client-step2-users').html(html);
      $("#et_id").val(et_id.toString());
    })
    // 上一步
    $('.set-client-prev').on('click', function() {
      $('.client-step2-users').empty();
      $('.client-step2').hide()
      $('.client-step1').show()
    })
    // 完成
    $('.set-client-confirm').on('click', function() {
      layui.use('form', function(){
        var form = layui.form;
        // 监听提交  
        form.on('submit(updLevelManagers)',function(data){
          var form2 = $('#form2').serialize();
          myAjaxPost(false, true, 'update_level_manager.html', form2, function (resp) {
            console.log(resp);
            if(resp.status == 'success') {
              layer.msg(resp.msg);
                setTimeout(function(){
                  window.location.reload();
                },1000);
                // layer.close(index);
            }else{
              alert(resp.msg);
            }
          });
          return false;
        })
      })
      // alert('confirm')
    })

  </script>
  <script type="text/javascript">
    $(".levelmanager-set").on('click',function(){
        location.href = 'setting.html';
    })

    $(document).ready(function() {

    })
  </script>
</body>
</html>